package cn.xk.user.service.impl;

import cn.xk.basic.exception.BusinessException;
import cn.xk.basic.util.Md5Utils;
import cn.xk.basic.util.StrUtils;
import cn.xk.org.domain.Employee;
import cn.xk.org.domain.Shop;
import cn.xk.org.domain.ShopAuditLog;
import cn.xk.org.mapper.EmployeeMapper;
import cn.xk.user.domain.Logininfo;
import cn.xk.user.domain.User;
import cn.xk.user.mapper.LogininfoMapper;
import cn.xk.user.mapper.UserMapper;
import cn.xk.user.service.IUserService;
import cn.xk.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private JavaMailSender javaMailSender;


    @Override
    public void phoneReigster(Map<String, String> map) {
        String phone = map.get("phone");
        String phoneCode = map.get("phoneCode");
        String pwd = map.get("pwd");
        String rePwd = map.get("rePwd");
        //1.空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode) || StringUtils.isEmpty(pwd) || StringUtils.isEmpty(rePwd)) {
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if (!pwd.equals(rePwd)) {
            throw new BusinessException("二次密码不一致");
        }
        //3.手机验证码是否过期，是否正确
        // 【业务键+电话号码，手机验证码：时间戳】
        Object obj = redisTemplate.opsForValue().get("register:" + phone);
        if (obj == null) {
            throw new BusinessException("手机验证码过期");
        }
        if (!phoneCode.equals(obj.toString().split(":")[0])) {
            throw new BusinessException("手机验证码错误");
        }
        //二.添加到数据库
        //当将一个对象转换成另一个对象时候，而且代码量的时候就用obj2Obj
        User user = map2User(map);
        Logininfo logininfo = user2Login(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void emailReigster(Map<String, String> map) throws MessagingException {
        String email = map.get("email");
        String password = map.get("password");
        String passwordRepeat = map.get("passwordRepeat");
        //1.空值校验
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)) {
            throw new BusinessException("信息不能为空");
        }
        //2.密码是否一致
        if (!password.equals(passwordRepeat)) {
            throw new BusinessException("二次密码不一致");
        }
        //二.添加到数据库
        //当将一个对象转换成另一个对象时候，而且代码量的时候就用obj2Obj
        User user = map2User(map);
        Logininfo logininfo = user2Login(user);
        //1.先添加t_logininfo
        logininfoMapper.save(logininfo);
        //2.再添加t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
        //3.发邮件给user通知他去激活
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        //true - 能够添加附件
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
        helper.setFrom("3170919649@qq.com"); //平台的邮箱
        helper.setSubject("用户激活邮件");
        //true - 能够再内容中编写html标签 - 会解析
        helper.setText("<h1>你的用户已经注册!!!</h1><img src='http://123.207.27.208/" +
                "' ><a href='http://127.0.0.1:8080/user/active/" + user.getId() + "'>点击该链接激活</a>", true);
        //收件人
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    @Override
    public String activeId(Long id) {
        User user = userMapper.loadById(id);
        user.setState(1);
        userMapper.update(user);
        Long logininfoId = user.getLogininfoId();
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);
        return "激活成功";
    }

    private Logininfo user2Login(User user) {
        Logininfo logininfo = new Logininfo();
        //根据属性同名原则
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);//用户手机号注册
        logininfo.setDisable(true);//手机注册默认启用
        return logininfo;
    }

    private User map2User(Map<String, String> map) {
        User user = new User();
        String phone = map.get("phone");
        user.setUsername(phone);
        user.setPhone(phone);
        //生成32位随机盐值
        String salt = StrUtils.getComplexRandomString(32);
        //加密加盐
        String md5pwd = Md5Utils.encrypByMd5(map.get("pwd") + salt);
        user.setSalt(salt);
        user.setPassword(md5pwd);
        user.setState(1);
        return user;


    }

}